// cron project main.go

package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"net/http"
	//"strconv"
	"time"
	"runtime"
	"sync"
)

//请求总次数
var total int
var totalMu sync.Mutex

//是否输出结果
var result bool

func request_cron(url string, t int) {
	totalMu.Lock()
	total++
	totalMu.Unlock()

	resp, err1 := http.Get(url)

	if err1 != nil {
		logTotal(err1.Error(),total,"Error")
		return

	}

	defer resp.Body.Close()

	data, err2 := ioutil.ReadAll(resp.Body)

	if err2 != nil {

		logTotal(err2.Error(),total,"Error")

		return

	}

	if result {
		logTotal(string(data),total,"Info")
	}
	ch <- url
	time.Sleep(time.Duration(t) * time.Second)
	go request_cron(url, t)
	return

}

/**
 输出日志
 */
func log(msg,msgType string){
	fmt.Println(fmt.Sprintf("%s:[%s] %s",time.Now().Format("2006-01-02 15:04:05"),msgType,msg))
}
/**
 输出日志带
 */
func logTotal(msg string,total int,msgType string){
	log(fmt.Sprintf("%d %s",total,msg),msgType)
}

//type MyFloat64 float64
var ch chan string

func main() {
	// fmt.Println(len)
	cpuNum := runtime.NumCPU()
	if cpuNum > 1{
		cpuNum --
	}
	runtime.GOMAXPROCS(cpuNum)
	url := flag.String("url", "", "请求的网址 URL")
	t := flag.Int("t", 1, "延时时间 Time")
	n := flag.Int("n", 1, "单次请求次数 Number")
	r := flag.String("r", "true", "是否输出结果 Output result")
	flag.Parse()
	Url := *url
	T := *t
	N := *n
	R := *r
	//default
	//请求的url地址
	if Url == "" {
		fmt.Println("Url is empty!")
		return
	}
	//是否输出结果
	if R == "true" {
		result = true
	} else {
		result = false
	}
	//fmt.Println(data["bbb"])
	total = 0
	log("Start..","Info")
	var i int
	ch = make(chan string, N)
	for i = 0; i < N; i++ {
		go request_cron(Url, T)
	}
	for d := range ch {
		log(d,"Url")
	}

}
